package com.example.spring_mybatis;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.example.spring_mybatis.model.BaseEntity;

import java.text.MessageFormat;
import java.util.*;


public class CodeGenerator {
    private final static String DB_USERNAME = "root" ;
    private final static String DB_HOST = "localhost" ;
    private final static String DB_PORT = "3306" ;
    private final static String DB_PASSWORD = "123456" ;
    private final static String DB_DATABASE = "beego" ;
    private final static String PROJECT_PATH = "com/example/spring_mybatis" ;

    public static void main(String[] args) {
        // 数据源配置
        FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(MessageFormat.format("jdbc:mysql://{0}:{1}/{2}?serverTimezone=GMT%2B8", DB_HOST, DB_PORT, DB_DATABASE), DB_USERNAME, DB_PASSWORD)
                // 1.全局配置
                .globalConfig(builder -> {
                    builder.author("水痕")        // 设置作者
//                            .enableSwagger()        // 开启 swagger 模式 默认值:false
                            .disableOpenDir()       // 禁止打开输出目录 默认值:true
                            .commentDate("yyyy-MM-dd HH:mm:ss") // 注释日期
                            .fileOverride() // 覆盖之前的文件
                            .dateType(DateType.ONLY_DATE)   //定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
                            .outputDir(System.getProperty("user.dir") + "/src/main/java"); // 指定输出目录

                })
                // 2.包配置
                .packageConfig(builder -> {
                    builder.parent(PROJECT_PATH.replace("/", ".")) // 父包模块名
                            .pathInfo(getPathInfo())
                            .controller("controller")   //Controller 包名 默认值:controller
                            .entity("model")           //Entity 包名 默认值:entity
                            .service("service")         //Service 包名 默认值:service
                            .mapper("mapper")           //Mapper 包名 默认值:mapper
                            // .other("model")
                            //.moduleName("xxx")        // 设置父包模块名 默认值:无
                            .pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper")); // 设置mapperXml生成路径
                    //默认存放在mapper的xml下
                })
                .injectionConfig(consumer -> {
                    String basePath = System.getProperty("user.dir");
                    List<CustomFile> customFiles = new ArrayList<>();
                    customFiles.add(new CustomFile.Builder().fileName("DTO.java")
                            .templatePath("templates/other/dto.java.vm")
                            .filePath(basePath+"/src/main/java/"+PROJECT_PATH+"/dto").build());
                    customFiles.add(new CustomFile.Builder().fileName("VO.java")
                            .templatePath("templates/other/vo.java.vm")
                            .filePath(basePath+"/src/main/java/"+PROJECT_PATH+"/vo").build());
                    consumer.customFile(customFiles);

                })
                // 策略配置
                .strategyConfig(builder -> {
                    builder.addInclude(scanner("表名，多个英文逗号分割").split(","))
                            //service策略配置
                            .serviceBuilder()
                            .formatServiceFileName("I%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            // 实体类策略配置
                            .entityBuilder()
                            .enableLombok() //开启lombok
                            .superClass(BaseEntity.class)
                            .addSuperEntityColumns("id", "created_at", "updated_at", "deleted_at") // 公共字段不需要抽取
                            .enableTableFieldAnnotation()// 属性加上注解说明
                            // 关于控制器的
                            .controllerBuilder() //controller 策略配置
                            .formatFileName("%sController")
                            .enableRestStyle() // 开启RestController注解
                            // 关于mapper的
                            .mapperBuilder()// mapper策略配置
                            .formatMapperFileName("%sMapper")
                            .formatXmlFileName("%sMapper");
                });
        fastAutoGenerator.execute();

    }

    private static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 配置生成路径
     *
     * @return
     */
    private static Map<OutputFile, String> getPathInfo() {
        Map<OutputFile, String> pathInfo = new HashMap<>();
        String path = "/src/main/java/" + PROJECT_PATH;
        pathInfo.put(OutputFile.entity, System.getProperty("user.dir") + path + "/model");
        pathInfo.put(OutputFile.mapper, System.getProperty("user.dir") + path + "/mapper");
        pathInfo.put(OutputFile.service, System.getProperty("user.dir") + path + "/service");
        pathInfo.put(OutputFile.serviceImpl, System.getProperty("user.dir") + path + "/service/impl");
        pathInfo.put(OutputFile.controller, System.getProperty("user.dir") + path + "/controller");
        pathInfo.put(OutputFile.xml, System.getProperty("user.dir") + "/src/main/resources/mapper");
        return pathInfo;
    }
}